<template>
  <div class="percent-container">
    <span ref="numberGrow">0</span>
    <span>%</span>
    <div v-if="isShowText" class="text_container" :style="{transform: scaleX}">{{currentLabelText}}</div>
  </div>
</template>

<script>
export default {
  props: {
    percent: {
      type: Number,
      default: 0
    },
    isShowText: {
      type: Boolean,
      default: true
    },
    labelText: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      scaleX: '',
      currentLabelText: '',
      t1: null,
      t2: null,
      t3: null
    }
  },
  watch: {
    percent(newVal, oldValue) {
      this.numberGrow(this.$refs.numberGrow, newVal, oldValue)
      this.handleTransform()
    }
  },
  created() {
    this.currentLabelText = this.labelText
  },
  methods: {
    numberGrow(el, newVal, oldValue) {
      const step = 1
      let start = oldValue
      let end = newVal
      if (start < end) {
        this.t1 = setInterval(() => {
          el.innerHTML = start
          start += step
          if (start > end) {
            clearInterval(this.t1)
            this.t1 = null
          }
        }, 10)
      } else {
        this.t2 = setInterval(() => {
          el.innerHTML = start
          start -= step
          if (start < end) {
            clearInterval(this.t2)
            this.t2 = null
          }
        }, 10)
      }
    },

    handleTransform() {
      const scaleXStep = 0.042
      let start = 0.2
      let secondStart = 1
      let flag = 0
      this.t3 = setInterval(() => {
        flag += scaleXStep
        if (flag <= 1) {
          secondStart -= scaleXStep
          this.scaleX = `scaleX(${secondStart})`
        }
        if (flag > 1 && flag <= 1.8) {
          start += scaleXStep
          this.currentLabelText = this.labelText
          this.scaleX = `scaleX(${start})`
        }
        if (flag > 1.8) {
          window.clearInterval(this.t3)
          this.t3 = null
        }
      }, 21)
    }
  },

  beforeDestroy() {
    clearInterval(this.t1)
    this.t1 = null
    clearInterval(this.t2)
    this.t2 = null
    clearInterval(this.t3)
    this.t3 = null
  }
}
</script>

<style  lang="scss" scoped>
.percent-container {
  color: #ffffff;
  width: 100px;
  .text_container {
    text-align: center;
  }
}
</style>
